package com.aruba.attendance.initial.view

import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.fadeIn
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import com.aruba.attendance.R
import com.aruba.attendance.ui.widget.datepicker.DataHourTimePicker
import kotlinx.coroutines.delay

/**
 * 选择上下班时间
 * Created by aruba on 2023/2/10.
 */
@OptIn(ExperimentalAnimationApi::class)
@Composable
fun TimeSelectView(
    initialStartTime: String = "",
    initialEndTime: String = "",
    timeSelect: (startTime: String, endTime: String) -> Unit,
    buttonContent: @Composable RowScope.() -> Unit = {
        Text(text = "sure")
    },
    hintContent: @Composable (ColumnScope.() -> Unit)? = null
) {
    // 小时数据
    val hours = remember {
        ArrayList<String>(24).apply {
            for (i in 0..23) {
                if (i < 10)
                    add("0${i}时")
                else
                    add("${i}时")
            }
        }
    }
    // 分数据
    val minutes = remember {
        val minStep = 5
        ArrayList<String>(60 / minStep).apply {
            for (i in 0..59 step minStep) {
                if (i < 10)
                    add("0${i}分")
                else
                    add("${i}分")
            }
        }
    }

    // 是否选择了上班时间
    var isSelectedStartTime by remember { mutableStateOf(false) }
//    var canClick by remember { mutableStateOf(true) }
    var visible by remember { mutableStateOf(false) }
    val targetStartHourIndex = remember { mutableStateOf(0) }
    val targetStartMinuteIndex = remember { mutableStateOf(0) }
    val targetEndHourIndex = remember { mutableStateOf(0) }
    val targetEndMinuteIndex = remember { mutableStateOf(0) }

    // 解析时间方法
    val parseHourAndMin: (String, MutableState<Int>, MutableState<Int>) -> Unit =
        { time, targetHourIndex, targetMinIndex ->
            if (time.isNotEmpty()) {
                val split = time.split("时")
                require(split.size == 2)

                targetHourIndex.value = hours.indexOf(split[0] + "时")
                targetMinIndex.value = minutes.indexOf(split[1])
            }
        }

    LaunchedEffect(Unit) {
        // 解析初始时间
        parseHourAndMin(initialStartTime, targetStartHourIndex, targetStartMinuteIndex)
        // 解析结束时间
        parseHourAndMin(initialEndTime, targetEndHourIndex, targetEndMinuteIndex)

        // 由于滚动有一个突兀，利用一个可见动画解决
        delay(500)
        visible = true;
    }

    AnimatedVisibility(
        visible = visible,
        enter = fadeIn()
    ) {
        Column(
            modifier = Modifier.wrapContentSize(),
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Center
        ) {

            // 提示标题
            AnimatedContent(targetState = isSelectedStartTime) { state ->
                Text(
                    text = buildAnnotatedString {
                        val content = if (!state) stringResource(id = R.string.title_start_time)
                        else stringResource(id = R.string.title_end_time)

                        append(content.substring(0, 3))
                        withStyle(
                            style = MaterialTheme.typography.titleLarge.toSpanStyle()
                                .copy(fontWeight = FontWeight.ExtraBold)
                        ) {
                            append(content.substring(3, 5))
                        }

                        append(content.substring(5))
                    },
                    style = MaterialTheme.typography.titleLarge,
                    modifier = Modifier.padding(bottom = 15.dp)
                )
            }

            // 时间选择器
            if (!isSelectedStartTime) {
                // 设置上班时间
                DataHourTimePicker(
                    hours, minutes,
                    targetHourIndex = targetStartHourIndex,
                    targetMinuteIndex = targetStartMinuteIndex
                )
            } else {
                // 设置下班时间
                DataHourTimePicker(
                    hours, minutes,
                    targetHourIndex = targetEndHourIndex,
                    targetMinuteIndex = targetEndMinuteIndex
                )
            }

            // 确认按钮
            Button(
                onClick = {
                    if (!isSelectedStartTime) {
                        // 更新为选过上班时间的状态
                        isSelectedStartTime = true
                    } else {
                        // 将上下班时间回调出去
                        timeSelect(
                            hours[targetStartHourIndex.value] + minutes[targetStartMinuteIndex.value],
                            hours[targetEndHourIndex.value] + minutes[targetEndMinuteIndex.value]
                        )
//                        canClick = false
                    }
                },
//                enabled = canClick,
                modifier = Modifier.padding(top = 30.dp),
                contentPadding = PaddingValues(50.dp, 5.dp, 50.dp, 5.dp)
            ) {
                CompositionLocalProvider(LocalTextStyle provides MaterialTheme.typography.bodyLarge) {
                    buttonContent()
                }
            }

            hintContent?.invoke(this)
        }
    }
}